﻿using System;

namespace Needle.Utils.Collections
{
    /// <summary>
    /// A keyed binding list with a user supplied item to key conversion function.
    /// this function must be pure functional, meaning it should always return 
    /// the same key for the same item instance.
    /// </summary>
    public class KeyedBindingList<TKey, TItem> : System.ComponentModel.BindingList<TItem>
    {
        private KeyedCollection<TKey, TItem> list;
        private ReadOnlyIndexer<TKey, TItem> indexer;

        /// <summary>
        /// 
        /// </summary>
        public KeyedBindingList(Converter<TItem,TKey> itemToKey)
            : base( new KeyedCollection<TKey, TItem>(itemToKey)) 
        {
            this.list = this.Items as KeyedCollection<TKey, TItem>;
            this.indexer = new ReadOnlyIndexer<TKey, TItem>(key => list[key]);
        }

        /// <summary>
        /// Indexes items by key.
        /// </summary>
        public ReadOnlyIndexer<TKey, TItem> Item
        {
            get { return indexer; }
        }

    }
}
